# encoding: utf-8
from flask import render_template, flash, redirect, url_for
from . import article
from ..forms import ArticleForm
from ..models import Category, Article
from flask_login import current_user
from flask_login import login_required

@article.route("/add", methods=["GET", "POST"])
@login_required
def add():
    form = ArticleForm()
    # 获取分类类别
    category_list = Category.queryAllbyTuple()
    form.setCategory(category_list)
    print(category_list)
    # 判断category_id是否存在，如果存在则转换成int类型
    if form.category_id.data != "None":
        form.category_id.data = int(form.category_id.data)
    else:
        form.category_id.data = ""
    if form.validate_on_submit():
        title = form.title.data
        content = form.content.data
        category_id = form.category_id.data
        author_id = int(current_user.get_id())

        # 添加文章
        article = Article(title=title, content=content, category_id=category_id, author_id=author_id)
        article.add()

        # 返回首页
        return redirect(url_for("article.add"))
    else:
        if form.errors.get("title"):
            flash(form.errors.get("title"))
        if form.errors.get("category_id"):
            flash(form.errors.get("category_id"))
        if form.errors.get("content"):
            flash(form.errors.get("content"))
    return render_template("article_save.html", form=form)